const url = require("url");
const Layer = require("./layer");
const Route = require("./route");
function Router() {
  this.stack = [];
}
Router.prototype.get = function (path, handlers) {
  const route = new Route();
  const layer = new Layer(path, route.dispatch.bind(route));

  layer.route = route; // 当调用路由方法时，会产生一个route

  this.stack.push(layer);
  route.get(handlers); // 让里层的route 记住用户的方法
};
Router.prototype.handle = function (req, res, out) {
  let { pathname } = url.parse(req.url);
  let idx = 0;

  const next = () => {
    if (idx >= this.stack.length) return out(); // 递归的终止条件
    let layer = this.stack[idx++];
    if (layer.match(pathname)) {
      // route.dispatch
      layer.handle_request(req, res, next);
    } else {
      next();
    }
  };

  next();
};

module.exports = Router;
